package app.cloudstringers;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;

import model.FileFormat;
import model.UploadItem;
import utils.Utils;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.learnncode.mediachooser.activity.HomeFragmentActivity;

import controller.CheckHBAsync;
import controller.HomeAsync;
import controller.LoginAsync;
import controller.UploadItemAsync;
import define.Constants;
import define.DefaultValue;
import define.Key;
import define.MobileAlbum;
import define.SharedPreference;
import define.Status;

public class Home extends Activity {
	/**
	 * String section
	 */
	public static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200;
	public static final int PICK_FILES = 300;

	public static String FIRMWARE_VERSION = "0", BUYSELL = null, ID = null;

	/**
	 * Data section
	 */
	public static LinkedList<Long> mLlSumOfFileSizes = new LinkedList<Long>();
	public static LinkedList<UploadItem> mLlItems = new LinkedList<UploadItem>();

	/**
	 * View section
	 */
	private AlertDialog.Builder mAdLogout, mAdExit, mAdPermission,
	mAdStopUploadTask;
	// private ImageButton mIbtnUpload, mIbtnPlayVideo;
	// private ImageView mIvPlayVideo;
	public static TextView mTvCardStatus;

	/**
	 * Others section
	 */
	public static Context context;
	private SharedPreferences.Editor mSpEditor;
	private SharedPreferences mSpSettings;
	private UploadItemAsync uploadItemAsync;

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case PICK_FILES:
			if (data != null) {
				clearData();

				/**
				 * Check video file format & Begin upload the video
				 */

				/**
				 * *.mts, *.mov, *.mpg, *.mp4, *.wmv
				 */
				for (String path : data.getStringArrayListExtra("list")) {
					checkFileFormatAndAddItem(data, path);
				}

				if (resultCode == RESULT_OK) {
					// TODO Compress the video before uploading to the server
					// Intent intent = new Intent(this, CompressingMedia.class);
					// intent.putExtra("file_path", mLlItems.get(0).getPath());
					// startActivity(intent);

					// Call new thread to use Upload API
					uploadItemAsync = new UploadItemAsync(this);
					uploadItemAsync.execute(Login.USER_NAME, ID,
							mLlItems.size() + "");
				} else if (resultCode == RESULT_CANCELED) {
					// User cancelled the video capture
					Toast.makeText(this, "Cancelled choosing video.",
							Toast.LENGTH_SHORT).show();
				} else {
					// Video capture failed, advise user
					// Warning : Camera failed :
					Toast.makeText(this, "Warning : Camera failed",
							Toast.LENGTH_SHORT).show();
				}
			}
			break;
		case CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE:
			if (resultCode == RESULT_OK) {
				clearData();

				String filePath = Constants.utils.getRealPathFromURI(
						this, data.getData());
				checkFileFormatAndAddItem(data, filePath);

				// Call new thread to use Upload API
				new UploadItemAsync(this).execute(Login.USER_NAME, ID, "1");

				// showVideoInfoDialog(fileName);
			} else if (resultCode == RESULT_CANCELED) {
				// User cancelled the video capture
				Toast.makeText(this, "Cancelled the video capture",
						Toast.LENGTH_SHORT).show();
			} else {
				// Video capture failed, advise user
				// Warning : Camera failed :
				Toast.makeText(this, "Warning : Camera failed",
						Toast.LENGTH_SHORT).show();
			}
			break;
		default:
			break;
		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	/**
	 * Clicked button
	 */
	public void onClickHome(View v) {
		switch (v.getId()) {
		case R.id.ibtn_camera_in_home:
			if (MobileAlbum.CAN_LEAVE == true) {
				// New intent to Camera feature
				Intent mIntentCamera = new Intent(
						MediaStore.ACTION_IMAGE_CAPTURE);
	
				// create a file to save the video
				Uri mUriFile = Uri
						.fromFile((new File((new Date()).toString())));
	
				// set the image file name
				mIntentCamera.putExtra(MediaStore.EXTRA_OUTPUT, mUriFile);
	
				// start the Video Capture Intent
				startActivityForResult(mIntentCamera,
						CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE);
			} else {
				mAdStopUploadTask.show();
			}
			break;
		case R.id.ibtn_logout_in_home:
			if (MobileAlbum.CAN_LEAVE == true) {
				mAdLogout.show();
			} else {
				mAdStopUploadTask.show();
			}
			break;
		case R.id.ibtn_mobile_album_in_home:
			if (MobileAlbum.CAN_LEAVE == true) {
				// New intent to choose multiple video files
				Intent mIntentMobileAlbum = new Intent(this,
						HomeFragmentActivity.class);
				startActivityForResult(mIntentMobileAlbum, PICK_FILES);
			} else {
				mAdStopUploadTask.show();
			}
			break;
		case R.id.ibtn_status:
			if (MobileAlbum.CAN_LEAVE == true) {
				// New intent to StatusTab
				Intent mIntentStatus = new Intent(Home.this, StatusTab.class);
				finish();
				startActivity(mIntentStatus);
			} else {
				mAdStopUploadTask.show();
			}
			break;
		case R.id.ibtn_my_video:
			if (MobileAlbum.CAN_LEAVE == true) {
				// Check account, suitable for show Permission Dialog or not?
				if (BUYSELL.equals(Key.KEY_CANNOT_BUY_CANNOT_SELL)
						|| BUYSELL.equals(Key.KEY_CAN_BUY_CANNOT_SELL)) {
					mAdPermission.show();
				} else {
					// New intent to VieoTab
					finish();
					startActivity(new Intent(Home.this, MyVideoTab.class));
				}
			} else {
				mAdStopUploadTask.show();
			}
			break;
		case R.id.ibtn_task_manager:
			finish();
			startActivity(new Intent(Home.this, TaskManager.class));
			break;
		default:
			break;
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.page_home);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);

		context = Home.this;
		
		// Initial alert dialogs
		initialAlertDialog();
		initialVariables();

		// Other tools
		Constants.utils = new Utils(this);
		Utils.initialConnectionDialog(this);

		if (LoginAsync.mTimerNextPageTranslation != null) {
			LoginAsync.mTimerNextPageTranslation.cancel();
			LoginAsync.mTimerNextPageTranslation = null;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK)) {
			mAdExit.show();
		}

		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onResume() {
		super.onResume();

		// Check network exists or not
		if (Constants.utils.isNetworkOnline()) {
			// Get data from shared preference
			mSpSettings = getSharedPreferences(SharedPreference.PREFS,
					Context.MODE_PRIVATE);
			mSpEditor = mSpSettings.edit();

			// Get ID & sell
			FIRMWARE_VERSION = mSpSettings.getString(
					SharedPreference.PREFS_KEY_FIRMWARE_VERSION, 0 + "");
			BUYSELL = mSpSettings.getString(SharedPreference.PREFS_KEY_SELL,
					Key.KEY_CANNOT_BUY_CANNOT_SELL + "");
			ID = mSpSettings.getString(SharedPreference.PREFS_KEY_GLOBAL_ID,
					DefaultValue.DEFAULT_GLOBAL_ID + "");

			/**
			 * Check firmware version is not equal 0 Show message notify the
			 * user need update version
			 */
			FIRMWARE_VERSION = Utils.getNumberOfString(FIRMWARE_VERSION);
			if (Float.valueOf(FIRMWARE_VERSION) != DefaultValue.DEFAULT_FIRMWARE_VERSION) {
				Toast.makeText(this, "Firmware already had new version : " + FIRMWARE_VERSION
						+ " !",
						Toast.LENGTH_SHORT).show();
			}
			/**
			 * Home information
			 */
			// Call API thread
			new HomeAsync(this).execute(ID);

			/**
			 * HB information
			 */
			// Call API thread to consider
			// Card was connected or disconnected
			// Call Checking HB process
			// Send
			// - Flag
			// - ID
			// - STATUS
			new CheckHBAsync(this).execute(ID, Status.STATUS_HB + "");
		} else {
			Utils.hideConnectionDialog();
			Utils.showConnectionDialog();
		}
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			if (UploadItemAsync.mDialog != null) {
				if (!UploadItemAsync.mDialog.isShowing()) {
					UploadItemAsync.mDialog.show();
				} else {
					UploadItemAsync.mDialog.hide();
				}
			}
		}

		return super.onTouchEvent(event);
	}

	/**
	 * Initial methods
	 */
	private void initialAlertDialog() {
		mAdLogout = new AlertDialog.Builder(this);
		mAdLogout.setTitle(getString(R.string.title_logout));
		mAdLogout.setCancelable(false);
		mAdLogout.setMessage(getString(R.string.content_logout));
		mAdLogout.setPositiveButton(R.string.yes,
				new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog9, int whichButton) {
				Login.GLOBAL_ID = DefaultValue.DEFAULT_GLOBAL_ID + "";
				Login.USER_NAME = null;
				Login.PASWORD = null;

				// Put data to shared preference
				mSpEditor.putString(
						SharedPreference.PREFS_KEY_GLOBAL_ID,
						DefaultValue.DEFAULT_GLOBAL_ID + "");
				mSpEditor.commit();

				// New intent to login
				Intent intent = new Intent(Home.this, Login.class);
				finish();
				startActivity(intent);
			}
		});
		mAdLogout.setNegativeButton(R.string.no,
				new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
			}
		});

		mAdPermission = new AlertDialog.Builder(this);
		mAdPermission.setTitle(getString(R.string.title_permission));
		mAdPermission.setIcon(R.drawable.ibtn_error_normal);
		mAdPermission.setCancelable(false);
		mAdPermission.setMessage(getString(R.string.content_permission));
		mAdPermission.setPositiveButton(R.string.ok,
				new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog9, int whichButton) {
			}
		});

		mAdExit = new AlertDialog.Builder(Home.this);
		mAdExit.setTitle(R.string.title_exit);
		mAdExit.setIcon(R.drawable.ic_info_normal);
		mAdExit.setCancelable(false);
		mAdExit.setMessage(R.string.content_exit);
		mAdExit.setPositiveButton(R.string.ok,
				new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog9, int whichButton) {
				android.os.Process.killProcess(android.os.Process
						.myPid());
			}
		});
		mAdExit.setNegativeButton(R.string.cancel,
				new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog9, int whichButton) {
			}
		});

		mAdStopUploadTask = new AlertDialog.Builder(Home.this);
		mAdStopUploadTask.setTitle(R.string.title_stop_upload);
		mAdStopUploadTask.setIcon(R.drawable.ic_info_normal);
		mAdStopUploadTask.setCancelable(false);
		mAdStopUploadTask.setMessage(R.string.content_stop_upload);
		mAdStopUploadTask.setPositiveButton(R.string.ok,
				new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog9, int whichButton) {
				MobileAlbum.CAN_LEAVE = true;

				// Stop Uploading thread
				uploadItemAsync.cancel(true);
				UploadItemAsync.mDialog.dismiss();
				UploadItemAsync.mDialog = null;
			}
		});
		mAdStopUploadTask.setNegativeButton(R.string.cancel,
				new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog9, int whichButton) {
			}
		});
	}

	private void initialVariables() {
		mTvCardStatus = (TextView) findViewById(R.id.tv_card_status_in_home);
	}

	/**
	 * Basic methods
	 */

	private void checkFileFormatAndAddItem(Intent data, String path) {
		File mFile = new File(path);

		// Get file size, date modified
		long total_size = mFile.length();
		// Also, add to sum of file size array list to store value
		mLlSumOfFileSizes.add(total_size);

		long last_modified = mFile.lastModified();
		String LAST_MODIFIED_TIME = Utils.getDate(last_modified,
				define.Home.DATE_FORMAT);

		String[] elements = path.split("/");
		ArrayList<String> mAlFileNameWithExtension = new ArrayList<String>();
		for (int i = 0; i < elements.length; i++) {
			mAlFileNameWithExtension.add(elements[i]);
		}

		String[] fileNamesAndExtensions = mAlFileNameWithExtension.get(
				elements.length - 1).split("\\.");

		String fileName = fileNamesAndExtensions[0];
		String fileExtension = fileNamesAndExtensions[1];
		for (FileFormat string : FileFormat.values()) {
			if (fileExtension.toLowerCase().equals(string.toString())) {
				UploadItem uploadItem = new UploadItem(fileName + "."
						+ fileExtension, LAST_MODIFIED_TIME, path,
						String.valueOf(total_size));

				// Add these video files to array list
				mLlItems.add(uploadItem);
			}
		}
	}

	private void clearData() {
		if (mLlItems != null && !mLlItems.isEmpty()) {
			mLlItems.clear();
		}
		if (mLlSumOfFileSizes != null && !mLlSumOfFileSizes.isEmpty()) {
			mLlSumOfFileSizes.clear();
		}
	}
}